<template>
  <view class="record-item" @tap="recordItemTapFn">
    <view
      class="order-header"
      :class="{
        wait: [0, 10, 100].includes(record.orderStatus),
        runing: [200, 300, 400].includes(record.orderStatus),
        done: [1000, -100].includes(record.orderStatus),
      }"
    >
      <view class="order-channel-name"> {{ record.orderSource == 1 ? '线下' : record.channelTypeName }} </view>
      <view class="order-code">
        <view class="order-code-item" v-if="record.channelOrderCode">
          <text class="order-code-tag">渠道</text>
          <text
            class="order-code-text"
            @longpress.stop="copyText(record.channelOrderCode)"
            @click.stop="click(record)"
            @touchend="touchend"
            >{{ record.channelOrderCode }}</text
          >
        </view>
        <view class="order-code-item" v-if="record.orderCode">
          <text class="order-code-tag">自有</text>
          <text class="order-code-text" @longpress.stop="copyText(record.orderCode)" @click.stop="click(record)" @touchend="touchend">{{
            record.orderCode
          }}</text>
        </view>
      </view>
      <view class="order-status">{{ record.orderStatusName }}</view>
    </view>
    <view class="order-main">
      <!-- 车辆信息 -->
      <view class="order-license">
        <view class="car-series overflow-ellipsis">{{ record.carSeriesName || '暂无车系' }}</view>
        <view
          class="license-number"
          v-if="record.carLicenseNo"
          @longpress.stop="copyText(record.carLicenseNo)"
          @click.stop="click(record)"
          @touchend="touchend"
        >
          {{ record.carLicenseNo }}
        </view>
      </view>
      <!-- 订单标签 -->
      <orderItemTag :tags="record.orderLabelList" />
      <view class="divider" style="margin: 0 0 18rpx"></view>
      <!-- 取送车地址 -->
      <order-item-cell label="取送车地址">
        <orderItemSiteAddress :record="record" />
      </order-item-cell>
      <!-- 交/还车人 -->
      <order-item-cell label="交/还车人" style="margin-bottom: 2rpx">
        <view class="staff-list">
          <view class="staff-item give">
            <view class="icon">交</view>
            <orderItemStaff :staff-name="record.giveStaffName" :canEditStaff="canEditStaff" @edit="editStaffFn('giveStaff')" />
          </view>
          <view class="staff-item return">
            <view class="icon">还</view>
            <orderItemStaff :staff-name="record.returnStaffName" :canEditStaff="canEditReturnStaff" @edit="editStaffFn('returnStaff')" />
          </view>
        </view>
      </order-item-cell>
      <!-- 预取/预还 -->
      <order-item-cell label="预取/预还">
        <view class="order-lease-time">
          <view class="time-item">{{ timeFormat(record.startTime) }}</view>
          <view class="time-spilt">至</view>
          <view class="time-item">{{ timeFormat(record.endTime) }}</view>
        </view>
      </order-item-cell>
      <!-- 实取/实还 -->
      <order-item-cell label="实取/实还" v-if="record.actualStartTime">
        <view class="order-lease-time">
          <view class="time-item">{{ timeFormat(record.actualStartTime) }}</view>
          <view class="time-spilt">至</view>
          <view class="time-item">{{ timeFormat(record.actualEndTime) }}</view>
        </view>
      </order-item-cell>
      <!-- 承租人 -->
      <order-item-cell label="承租人" style="margin-bottom: 0">
        <view class="member-info-wrapper">
          <!-- 承租人信息 -->
          <view class="member-info" :style="{ width: 'calc(100% - 80rpx)' }">
            <view class="member-name overflow-ellipsis">{{ record.memberName }}</view>
            <view class="member-phone" @click.stop="dialPhone(record.memberPhone)" v-if="record.memberPhone">
              <view class="member-phone-text">{{ record.memberPhone }}</view>
              <view class="member-phone-icon"></view>
            </view>
          </view>
          <!-- 修改按钮 -->
          <view class="member-info-btn" v-if="canEditMemberInfo" @click.stop="onEditMemberClick">
            <view class="member-info-btn-text">修改</view>
            <view class="member-info-btn-icon"></view>
          </view>
        </view>
      </order-item-cell>
      <order-item-cell label="备注">
        <view class="remark-content">
          <text class="remark-info">{{ record.remark || '-' }}</text>
          <text v-if="record.remark" class="remark-btn" @click.stop="showRemarkModal(record.id)">更多</text>
        </view>
      </order-item-cell>
      <view style="height: 1rpx"></view>
    </view>
    <!-- 底部操作 -->
    <order-item-operates :record="record" :admin="employeeId" :isAdminRole="isAdminRole" @ok="emits('ok')" />

    <!-- 修改承租人选择浮框 -->
    <ve-popup :modelValue="editMemberPopupVisible" mode="bottom" @close="onEditMemberPopupClose">
      <view class="popup-btn-box" :style="{ height: record.memberType == 2 ? '456rpx' : '372rpx' }">
        <view class="popup-btn-header">
          <text>修改</text>
        </view>
        <view class="popup-btn-content">
          <view class="popup-btn" @click="editMemberFn">修改承租人信息</view>
          <view class="popup-btn" v-if="record.memberType == 2" @click="editCurrentMemberFn">修改已选承租人信息</view>
        </view>
      </view>
    </ve-popup>

    <!-- 修改承租人信息 -->
    <editLesseeMemberModal ref="editLesseeMemberModalRef" @ok="editLesseeSuccessFn" />
    <!-- 修改已选承租人信息 -->
    <EditCurrentMemberModal ref="editCurrentMemberModalRef" @ok="editLesseeSuccessFn" />
  </view>
</template>

<script setup>
  import { ref, computed } from 'vue'
  import orderItemCell from '@/pages/order/components/orderItemCellShort.vue'
  import orderItemStaff from '@/pages/order/components/orderItemStaff.vue'
  import orderItemTag from './orderItemTag.vue'
  import orderItemSiteAddress from '@/pages/order/components/orderItemSiteAddress.vue'
  import orderItemOperates from './orderItemOperates.vue'
  import editLesseeMemberModal from './modals/edit-lessee-member-modal.vue'
  import EditCurrentMemberModal from '@/pages/order/components/customer/edit-current-member-modal.vue'
  import dayjs from 'dayjs'

  import { getShortOrdrDetailsAPI } from '@/api/order/sOrder'
  import { dialPhone } from '@/utils'
  import { usePermission } from '@/hooks/usePermission'

  const islongPress = ref(false)
  // 复制
  const copyText = (e) => {
    islongPress.value = true
    uni.setClipboardData({
      data: e,
      success: function () {
        uni.showToast({
          title: '已复制',
          icon: 'none',
        })
      },
    })
  }
  const click = (i) => {
    if (islongPress.value == false) {
      // console.log("不是长按事件");
      recordItemTapFn()
    } else if (islongPress.value == true) {
      // console.log("长按事件");
    }
  }
  const touchend = () => {
    //延时执行为了防止 click() 还未判断 islongPress 的值就被置为 fasle
    setTimeout(() => {
      islongPress.value = false
    }, 200)
  }

  const props = defineProps({
    record: {
      type: Object,
      default: () => {},
    },
    employeeId: {
      type: String,
      default: '',
    },
    isAdminRole: {
      type: Boolean,
      default: false,
    },
  })

  // 日期格式化
  const timeFormat = (date) => {
    if (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    } else {
      return '-'
    }
  }

  const isNullOrRejected = (status) => status === 3 || status === null
  const isValidStatus = (status, type) => [10, 100].includes(status) || (type === 'returnStaff' && status === 200)
  // 待排车、待用车时，可变更交车人
  // 待排车、待用车、用车中时，可变更还车人
  const orderStaffCanClick = (type) => {
    const {
      isCarHouseKeepOpen,
      assignGiveCarStaffFlag,
      assignReturnCarStaffFlag,
      giveStaffStatus,
      returnStaffStatus,
      orderStatus,
      inProgressGiveWorkOrderFlag, // 交车工单是否进行中 1-进行中 0-未进行中
      inProgressReturnWorkOrderFlag, // 还车工单是否进行中 1-进行中 0-未进行中
      orderSource, //订单来源
      channelOrderMaintenance,
    } = props.record

    // 开启车管家
    if (isCarHouseKeepOpen === 1) {
      // 修改交车人
      if (type == 'giveStaff' && assignGiveCarStaffFlag == 1) {
        if (orderSource == 1) {
          return isValidStatus(orderStatus, type) && isNullOrRejected(giveStaffStatus) && usePermission('svmsapp:order:short-order.edit')
        } else {
          if (channelOrderMaintenance === 1 || channelOrderMaintenance === null) {
            return usePermission('svmsapp:order:short-order.edit')
          } else {
            return isValidStatus(orderStatus, type) && isNullOrRejected(giveStaffStatus) && usePermission('svmsapp:order:short-order.edit')
          }
        }
      }

      // 修改还车人
      if (type == 'returnStaff' && assignReturnCarStaffFlag === 1) {
        if (orderSource == 1) {
          return isValidStatus(orderStatus, type) && isNullOrRejected(returnStaffStatus) && usePermission('svmsapp:order:short-order.edit')
        } else {
          if (channelOrderMaintenance === 1 || channelOrderMaintenance === null) {
            return usePermission('svmsapp:order:short-order.edit')
          } else {
            return (
              isValidStatus(orderStatus, type) && isNullOrRejected(returnStaffStatus) && usePermission('svmsapp:order:short-order.edit')
            )
          }
        }
      }

      return false
    } else {
      if (type == 'giveStaff') {
        if (orderSource == 1) {
          return (
            [10, 100].includes(orderStatus) &&
            usePermission('svmsapp:order:short-order.edit') &&
            assignGiveCarStaffFlag === 1 &&
            inProgressGiveWorkOrderFlag === 0
          )
        } else {
          return usePermission('svmsapp:order:short-order.edit') && assignGiveCarStaffFlag === 1 && inProgressGiveWorkOrderFlag === 0
        }
      }
      if (type == 'returnStaff') {
        if (orderSource == 1) {
          return (
            [10, 100, 200].includes(orderStatus) &&
            usePermission('svmsapp:order:short-order.edit') &&
            assignReturnCarStaffFlag === 1 &&
            inProgressReturnWorkOrderFlag === 0
          )
        } else {
          return usePermission('svmsapp:order:short-order.edit') && assignReturnCarStaffFlag === 1 && inProgressReturnWorkOrderFlag === 0
        }
      }
    }
  }

  // 是否可以修改交车人
  const canEditStaff = computed(() => {
    return orderStaffCanClick('giveStaff')
  })
  // 是否可以修改交车人
  const canEditReturnStaff = computed(() => {
    return orderStaffCanClick('returnStaff')
  })

  // 是否可以修改承租人
  const canEditMemberInfo = computed(() => {
    return usePermission('svmsapp:order:short-order.edit') && [10, 100, 200, 300, 1000].includes(props.record.orderStatus)
  })

  const emits = defineEmits(['editStaffFn', 'editLesseeSuccessFn'])
  // 操作的是交车 or 还车人
  const editStaffFn = (type) => {
    emits('editStaffFn', type, props.record)
  }

  // 修改承租人
  const editMemberPopupVisible = ref(false)
  // 点击承租人修改按钮，开启浮框
  const onEditMemberClick = () => {
    uni.hideTabBar()
    editMemberPopupVisible.value = true
  }
  // 点击承租人修改按钮，关闭浮框
  const onEditMemberPopupClose = () => {
    editMemberPopupVisible.value = false
    uni.showTabBar()
  }

  // 修改承租人
  const editLesseeMemberModalRef = ref()
  const editMemberFn = () => {
    editLesseeMemberModalRef.value.open(props.record.id)
    onEditMemberPopupClose()
  }

  // 修改已选承租人信息
  const editCurrentMemberModalRef = ref()
  const editCurrentMemberFn = () => {
    const { record } = props
    if (!record.memberPhone || !record.memberName) {
      uni.showToast({ title: '请先填写承租人及联系电话', icon: 'none' })
      return
    }
    if (record.memberPhone.indexOf('*') != -1) {
      uni.showToast({ title: '手机号码带*无法在系统中找到该会员，请先填写正确的手机号码，再修改信息', icon: 'none' })
      return
    }
    editCurrentMemberModalRef.value.open(props.record)
    onEditMemberPopupClose()
  }

  // 修改承租人成功
  const editLesseeSuccessFn = () => {
    let orderId = props.record.id
    getShortOrdrDetailsAPI({ id: orderId }).then((res) => {
      let result = res.result
      let memberInfoDto = result.memberInfoDto || {}
      let orderInfo = result.orderInfo
      let temp = {
        ...props.record,
        // 个人用户
        memberPhone: orderInfo.memberPhone,
        memberName: orderInfo.memberName,
        memberType: orderInfo.memberType,
        // 企业用户
        clientId: orderInfo.clientId,
        clientName: orderInfo.clientName,
        memberId: orderInfo.memberId,
        // 通用
        cardType: memberInfoDto.cardType,
        cardNumber: memberInfoDto.cardNumber,
        // 驾驶证正反面信息
        driverFrontFileId: memberInfoDto.driverFrontFileId,
        driverReverseFileId: memberInfoDto.driverReverseFileId,
        // 身份证明正反面信息
        idCardFrontFileId: memberInfoDto.idCardFrontFileId,
        idCardReverseFileId: memberInfoDto.idCardReverseFileId,
      }
      emits('editLesseeSuccessFn', temp)
    })
  }
  // 点击卡片
  const recordItemTapFn = () => {
    const record = props.record
    if (usePermission('svmsapp:order:short-order.view')) {
      uni.navigateTo({
        url: `/pages/order/short-order/detail/index?id=${record.id}&orderId=${record.id}&bizType=1&orderStatus=${record.orderStatus}`,
      })
    }
  }
  // 跳转更多备注页面
  const showRemarkModal = (id) => {
    uni.navigateTo({
      url: '/pages/order/short-order/remark-list?id=' + id,
    })
  }
</script>

<style lang="less" scoped>
  .overflow-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .record-item {
    margin-bottom: 24rpx;
    border-radius: 8rpx;
    .order-header {
      display: flex;
      align-items: center;
      padding: 24rpx 22rpx 24rpx 24rpx;
      height: 112rpx;
      border-radius: 8rpx 8rpx 0 0;
      .order-channel-name {
        width: 64rpx;
        height: 64rpx;
        text-align: center;
        line-height: 64rpx;
        background-color: #3072f6;
        font-size: 24rpx;
        margin-right: 20rpx;
        border-radius: 4rpx;
        color: #ffffff;
      }
      .order-code {
        flex: 1;
        .order-code-item {
          font-size: 24rpx;
          color: #8491a8;
          line-height: 1;
          .order-code-tag {
            margin-right: 8rpx;
          }
          .order-code-text {
            color: #191c27;
          }
        }
      }
      .order-code-item + .order-code-item {
        margin-top: 16rpx;
      }
      .order-status {
        width: 100rpx; //ios
        text-align: right;
        font-size: 28rpx;
      }

      &.wait {
        background: linear-gradient(90deg, #fff3d5 0%, #ffffff 100%);
        color: #e59b1c;
      }

      &.runing {
        background: linear-gradient(90deg, #d5e5ff 0%, #ffffff 100%);
        color: #3072f6;
      }

      &.done {
        background: linear-gradient(90deg, #eaecef 0%, #ffffff 100%);
        color: #8491a8;
      }
    }
    .order-main {
      padding: 0 24rpx;
      background: #ffffff;
      .order-license {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 18rpx 0 0;
        line-height: 44rpx;
        .license-number {
          height: 44rpx;
          padding: 0 8rpx;
          background: #3072f6;
          border-radius: 4rpx;
          margin-left: 16rpx;
          color: #ffffff;
          font-size: 22rpx;
          font-weight: 600;
          flex-shrink: 0;
        }
        .car-series {
          height: 44rpx;
          font-size: 30rpx;
          font-weight: 600;
          color: #191c27;
        }
      }
      .divider {
        width: 100%;
        height: 2rpx;
        background: rgba(216, 216, 216, 0.3);
      }
      .staff-list {
        display: flex;
        flex-wrap: wrap;
        .staff-item {
          display: flex;
          max-width: 100%;
          margin-bottom: 14rpx;
          align-items: center;
          margin-right: 40rpx;
          .icon {
            width: 36rpx;
            height: 28rpx;
            line-height: 28rpx;
            border-radius: 4rpx 4rpx 4rpx 4rpx;
            font-weight: 700;
            font-size: 20rpx;
            text-align: center;
            margin-right: 8rpx;
            flex-shrink: 0;
          }
        }
        .staff-item.give {
          .icon {
            color: #00b42a;
            background: #e8ffea;
          }
        }
        .staff-item.return {
          .icon {
            color: #ff7d00;
            background: #fff7e8;
          }
        }
      }
      .order-lease-time {
        color: #191c27;
        display: flex;
        align-items: center;
        height: 24rpx;
        line-height: 24rpx;
        .time-item {
          flex-shrink: 0;
        }
        .time-spilt {
          margin: 0 24rpx;
        }
      }
      .member-info-wrapper {
        display: flex;
        align-items: flex-start;
        .member-info {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          align-items: baseline;
          .member-name {
            margin-right: 24rpx;
            line-height: 28rpx;
            word-wrap: break-word;
            margin-bottom: 12rpx;
          }
          .member-phone {
            display: inline-flex;
            align-items: center;
            margin-right: 24rpx;
            margin-bottom: 12rpx;
            .member-phone-icon {
              margin-left: 8rpx;
              width: 32rpx;
              height: 32rpx;
              background-image: url('@/static/icons/dial-phone.png');
              background-size: 100%;
            }
          }
        }
        .member-info-btn {
          display: flex;
          align-items: center;
          flex-shrink: 0;
          .member-info-btn-text {
            font-size: 24rpx;
            color: #3072f6;
            line-height: 24rpx;
          }
          .member-info-btn-icon {
            background-image: url('@/static/icons/arrow_right_1.png');
            background-size: 28rpx 28rpx;
            width: 22rpx;
            height: 28rpx;
            margin-left: 2rpx;
          }
        }
      }
    }
    .remark-content {
      display: flex;
    }
    .remark-info {
      font-size: 24rpx;
      color: #191c27;
      display: -webkit-box;
      width: 100%;
      word-break: break-all;
      text-overflow: ellipsis;
      overflow: hidden;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
    }
    .remark-btn {
      color: #3072f6;
      cursor: pointer;
      margin: 0 0 0 20rpx;
      flex-shrink: 0;
      font-size: 24rpx;
    }
  }
  .popup-btn-box {
    padding: 32rpx 40rpx;

    .popup-btn-header {
      font-size: 36rpx;
      font-weight: 600;
      color: #191c27;
      text-align: center;
      margin-bottom: 48rpx;
    }

    .popup-btn-content {
      .popup-btn {
        height: 84rpx;
        line-height: 84rpx;
        text-align: center;
        border-radius: 4rpx;
        background: #f3f7ff;
        font-size: 30rpx;
        font-weight: 400;
        color: #1d2129;

        &:active {
          background: rgba(213, 227, 255, 1);
        }
      }
      .popup-btn + .popup-btn {
        margin-top: 32rpx;
      }
    }
  }
</style>
